﻿using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace PMAF.K3Cloud.SCM.Bill.ServicePlugIn
{
    [HotUpdate]
    [Description("删除销售订单同步更新采购流水号当前数量")]
    public class SaleOrderDelete : AbstractOperationServicePlugIn
    {
        //加载需要的属性
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add("F_PMAF_IsShort");
            e.FieldKeys.Add("F_PMAF_PurchaseSN");
            e.FieldKeys.Add("F_PMAF_PurchaseSN_Id");
        }

        /// <summary>
        /// 事务开始前事件
        /// </summary>
        /// <param name="e"></param>
        public override void BeginOperationTransaction(BeginOperationTransactionArgs e)
        {
            foreach (DynamicObject entity in e.DataEntitys)
            {
                if (entity != null)
                {
                    //读取单据明细行
                    DynamicObjectCollection entry = (DynamicObjectCollection)entity["SaleOrderEntry"];
                    if(string.Equals(entity["FFormId"], "SAL_SaleOrder")){
                        foreach (DynamicObject row in entry)
                        {
                            var qty = Convert.ToInt32(row["Qty"]);          //销售数量
                            var purchaseId = Convert.ToInt32(row["F_PMAF_PurchaseSN_Id"]);   //流水号
                            if(purchaseId != 0)
                            {
                                //构建流水号字段
                                List<SelectorItemInfo> purchaseFields = new List<SelectorItemInfo>
                                {
                                    new SelectorItemInfo("F_PMAF_PurchaseSN_Id"),
                                    new SelectorItemInfo("F_PMAF_CurrentQty")
                                };
                                //流水号过滤条件
                                OQLFilter purchaseSnFilter = new OQLFilter
                                {
                                    new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", purchaseId) }
                                };
                                //查询流水号
                                DynamicObject[] purchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", purchaseFields, purchaseSnFilter);
                                //更新流水号当前数量
                                purchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToInt32(purchaseSns[0]["F_PMAF_CurrentQty"]) + qty;
                                //保存更新
                                BusinessDataServiceHelper.Save(Context, purchaseSns);
                            }
                        }
                    }
                }
            }
        }
    }
}
